/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package manager.helpers.validation;

import manager.helpers.validation.TextFieldValidator;
import javax.swing.JLabel;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/**
 *
 * @author diego1
 */
public class TextFieldValidationDocument extends PlainDocument {

    TextFieldValidator textFieldValidator;

    public TextFieldValidationDocument(TextFieldValidator newTextFieldValidator) {
        super();
        this.textFieldValidator = newTextFieldValidator;
    }

    @Override
    public void insertString(int offset, String str, AttributeSet a)
            throws BadLocationException {
        if (str == null) {
            return;
        }
        if (textFieldValidator.isUpper()) {
            str = str.toUpperCase();
        }
        if (textFieldValidator.getiMaxLength() <= 0) // aceitara qualquer no. de caracteres
        {
            super.insertString(offset, str, a);
            return;
        }
        int ilen = (getLength() + str.length());
        if (ilen <= textFieldValidator.getiMaxLength()) // se o comprimento final for menor...
        {
            super.insertString(offset, str, a);   // ...aceita str
        } else {
            if (getLength() == textFieldValidator.getiMaxLength()) {
                return; // nada a fazer
            }
            String newStr = str.substring(0, (textFieldValidator.getiMaxLength() - getLength()));
            super.insertString(offset, newStr, a);
        }
        textFieldValidator.validarCampo();
    }
}
